﻿Namespace ErrorHandling

    Module mError

        Private AddToErrorText As Boolean

        Sub UnhandledErrorHandler(ByVal sender As Object, ByVal args As UnhandledExceptionEventArgs)

            'If args.ExceptionObject.GetType() = Microsoft.DirectX.Direct3D.DeviceLostException Then Exit Sub

            'Handles any error not handled by a Try Catch statement

            'path to error.txt
            Dim err_file As String = Globals.sRootPath & "\error.txt"
            'delete any existing error.txt
            If Not AddToErrorText Then
                If System.IO.File.Exists(err_file) Then System.IO.File.Delete(err_file)
            End If

            'create new error.txt
            Dim BW As System.IO.TextWriter = New System.IO.StreamWriter(err_file, AddToErrorText)

            'this is the text we want in the file
            Dim strTxt As String = (vbCrLf & vbCrLf & "[============================================================]" & vbCrLf & vbCrLf) & _
            ("Error Message: " & args.ExceptionObject.Message & vbCrLf) & _
            ("Exception:" & args.ExceptionObject.InnerException & vbCrLf) & _
            ("Source: " & args.ExceptionObject.Source & vbCrLf) & _
            ("Target Site: " & args.ExceptionObject.TargetSite.Name & vbCrLf) & _
            ("Stack trace follows... " & vbCrLf & args.ExceptionObject.StackTrace & vbCrLf) & _
            (vbCrLf & vbCrLf & "[============================================================]" & vbCrLf & vbCrLf)
            'write to the file and close it
            BW.Write((DateTime.Now.ToString & "|" & Globals.sIP & "|]==" & vbCrLf & vbCrLf) & strTxt)
            BW.Flush()
            BW.Close()

            'Dim err_report_url As String = "http://" & Globals.sIP & "/?q=errorreport&r=" & (Replace(strTxt, vbCrLf, "<BR>"))
            'Shell(err_report_url)

            AddToErrorText = True

            MsgBox("Critical error!" & vbCrLf & "Will upload report on next load!" & vbCrLf & vbCrLf & strTxt, MsgBoxStyle.Critical, "MirEvolution Error")

            Application.Exit()
            End

        End Sub

    End Module

End Namespace